<template>
  <div class="app-container">
    <!-- <h3>药品种类管理</h3> -->
    <!-- 查询框 -->
    <div class="filter-container">
      <el-input
        v-model="pageParam.superSearchKeyWord"
        style="width: 200px;"
        placeholder="关键字查询..."
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @input="handleFilter"
      />
      <el-select
        v-model="pageParam.model.categroyId"
        style="width: 140;"
        class="filter-item"
        placeholder="药品分类"
        @change="categoryChange"
      >
        <el-option v-for="item in newsCategoryList" :key="item.id" :label="item.categroyName" :value="item.id" />
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" fit highlight-current-row style="width: 100%;" @sort-change="sortChange">

      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">

            <el-form-item label="药品名称">
              <span>{{ row.medicinalName }}</span>
            </el-form-item>

<!--            <el-form-item label="类别">-->
<!--              <span>{{ row.categroyId }}</span>-->
<!--            </el-form-item>-->

            <el-form-item label="库存">
              <span>{{ row.stock }}</span>
            </el-form-item>

            <el-form-item label="销量">
              <span>{{ row.salesVolume }}</span>
            </el-form-item>

            <el-form-item label="单价">
              <span>{{ row.price }}</span>
            </el-form-item>
            <el-form-item label="规格">
              <span>{{ row.standards }}</span>
            </el-form-item>

            <el-form-item label="用量">
              <span>{{ row.dosage }}</span>
            </el-form-item>

            <el-form-item label="成分">
              <span>{{ row.component }}</span>
            </el-form-item>

            <el-form-item label="产品编号">
              <span>{{ row.productNumber }}</span>
            </el-form-item>

            <el-form-item label="批准文号">
              <span>{{ row.approvalNumber }}</span>
            </el-form-item>
            <el-form-item label="类别名称">
              <span>{{ row.categroyName }}</span>
            </el-form-item>

            <el-form-item label="生产厂家">
              <span>{{ row.manufacturer }}</span>
            </el-form-item>

            <el-form-item label="主要作用">
              <span>{{ row.functions }}</span>
            </el-form-item>

            <el-form-item label="注意事项">
              <span>{{ row.note }}</span>
            </el-form-item>

            <el-form-item label="创建日期">
              <span>{{ row.createTime }}</span>
            </el-form-item>

            <el-form-item label="创建人ID">
              <span>{{ row.createId }}</span>
            </el-form-item>

            <el-form-item label="修改日期">
              <span>{{ row.updataTime }}</span>
            </el-form-item>

            <el-form-item label="修改人">
              <span>{{ row.updataId }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <!-- 表格字段 -->
      <el-table-column prop="medicinalName" label="药品名称" />
      <!-- <el-table-column prop="categroyId" label="类别">
			</el-table-column> -->
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="price" label="单价" />
      <el-tooltip :content="'Switch value: ' + value" placement="top">
        <el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949" active-value="100" inactive-value="0" />
      </el-tooltip>

      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button v-if="row.isShelf==1" size="small" type="primary" @click="handleShelf(row)">上架</el-button>
          <el-button v-if="row.isShelf==0" size="small" type="danger" @click="handleShelf(row)">下架</el-button>
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row,$index)" v-permission="['admin']">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getListByPage"
    />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="药品分类" prop="categroyId">
          <el-select v-model="temp.categroyId" placeholder="请选择药品分类">
            <el-option v-for="item in newsCategoryList" :key="item.id" :label="item.categroyName" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- 弹窗 -->
        <el-form-item label="药品名称" prop="medicinalName">
          <el-input v-model="temp.medicinalName" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="temp.stock" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="temp.price" />
        </el-form-item>
        <el-form-item label="规格" prop="standards">
          <el-input v-model="temp.standards" />
        </el-form-item>
        <el-form-item label="用量" prop="dosage">
          <el-input v-model="temp.dosage" />
        </el-form-item>
        <el-form-item label="成分" prop="component">
          <el-input v-model="temp.component" />
        </el-form-item>
        <el-form-item label="产品编号" prop="productNumber">
          <el-input v-model="temp.productNumber" />
        </el-form-item>
        <el-form-item label="批准文号" prop="approvalNumber">
          <el-input v-model="temp.approvalNumber" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="temp.manufacturer" />
        </el-form-item>
        <el-form-item label="主要作用" prop="functions">
          <el-input v-model="temp.functions" />
        </el-form-item>
        <el-form-item label="注意事项" prop="note">
          <el-input v-model="temp.note" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  mapGetters,
  mapState
} from 'vuex'

import {
  getToken
} from '@/utils/auth'

import {
  searchSomeMedicinalPage,
  insertOne,
  deleteOne,
  updateOne,
  selectOne,
  shelfMedicinal
} from '@/api/medicinal/medicinal'

import {
  searchSomeMedicinalCategroyPage
} from '@/api/medicinal/medicinalCategroy'

// 导入组件  记得声明组件
import Pagination from '@/components/Pagination'

export default {
  components: { // 在这里声明组件
    Pagination
  },
  computed: {
    ...mapGetters({
      'categroyName': 'categroyName'
    }),
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  data() {
    return {
      dialogVisible: false,
      list: [], // 列表数据
      total: 0,
      listQuery: { // 分页 排序  查询参数
        pageNum: 1,
        pageSize: 5
      },
      fieldQuery: { // 按字段查询
        realName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      temp: {
        id: '',
        medicinalName: '',
        categroyId: '',
        stock: '',
        salesVolume: '',
        price: '',
        standards: '',
        dosage: '',
        component: '',
        productNumber: '',
        approvalNumber: '',
        manufacturer: '',
        functions: '',
        note: '',
        createTime: '',
        createId: '',
        updataTime: '',
        updataId: '',
        isShelf: '',
        isCheck: '',
        isDelete: ''
      },
      tempImageList: [],
      newsCategoryList: [],
      rules: {},
      pageParam: {
        pageNum: 1,
        pageSize: 5,
        model: {
          categroyId: ''

        },
        orderParams: [],
        superSearchKeyWord: ''
      },
      roleList: []
    }
  },
  created() {
    this.getListByPage()
  },
  mounted() {
    this.getNewsCategoryList()
  },
  methods: {
    sortChange(val) {
      // console.log("排序参数",val)
      const prop = val.prop
      const order = val.order === 'ascending' ? 'asc' : 'desc'
      const orderParam = prop + ' ' + order
      // console.log(orderParam)
      for (let i = 0; i < this.pageParam.orderParams.length; i++) {
        if (this.pageParam.orderParams[i].indexOf(prop) > -1) {
          this.pageParam.orderParams.splice(i, 1)
        }
      }
      this.pageParam.orderParams.push(orderParam)
      console.log(this.pageParam.orderParams)
      this.getListByPage()
    },
    getNewsCategoryList() {
      const pageNum = 1
      const pageSize = 1000
      const orderParams = []
      const model = {
        checkStatus: 1 // 只查询 已经审核通过的分类
      }
      const pageParam = {
        pageNum,
        pageSize,
        orderParams,
        model
      }
      searchSomeMedicinalCategroyPage(pageParam).then(res => {
        // console.log(res)
        this.newsCategoryList = res.content.list
      }).catch(err => {
        console.log(err)
      })
    },
    getListByPage() {
      this.pageParam.pageNum = this.listQuery.pageNum
      this.pageParam.pageSize = this.listQuery.pageSize

      console.log(this.pageParam.orderParams)

      searchSomeMedicinalPage(this.pageParam).then(res => {
        // console.log(res)
        this.list = res.content.list
        this.total = res.content.total
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getListByPage()
    },
    handleCreate() {
      this.tempImageList = []
      // this.$refs.imagesUpload.clearFiles()
      this.resetTemp()
      this.getNewsCategoryList()
      // console.log(this.userName)
      this.temp.createUserNickName = this.storeNickName
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      console.log('edit:' + row)
      this.temp = Object.assign({}, row) // copy obj
      this.temp.id = row.id
      this.dialogStatus = 'update'
      // this.getTempImageList() // 展示商品图片列表
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      const temp = {
        id: row.id
      }

      deleteOne(temp).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
      })
    },
    handleShelf(row) {
      shelfMedicinal(row).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          insertOne(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateOne(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: '',
        medicinalName: '',
        categroyId: '',
        stock: '',
        salesVolume: '',
        price: '',
        standards: '',
        dosage: '',
        component: '',
        productNumber: '',
        approvalNumber: '',
        manufacturer: '',
        functions: '',
        note: '',
        createTime: '',
        createId: '',
        updataTime: '',
        updataId: '',
        isShelf: '',
        isCheck: '',
        isDelete: ''
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)

      const imageUrl = file.response == undefined ? file.url.replace('blob:', '') : file.response.content
      // let imageUrl = ''
      const productImageData = {
        imageUrl: imageUrl
      }
      deleteSomeProductimageTrueByCondition(productImageData).then(() => {})
    },
    onEditorBlur(quill) {
      // console.log('editor blur!', quill)
    },
    onEditorFocus(quill) {
      // console.log('editor focus!', quill)
    },
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    },
    onEditorChange({
      quill,
      html,
      text
    }) {
      // console.log('editor change!', quill, html, text)
      this.temp.description = html
    },
    categoryChange() {
      console.log(this.pageParam.model)
      this.getListByPage()
    }
  }
}
</script>

<style>
	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {
		width: 90px;
		color: #99a9bf;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
